<template>
    <div class="container">
        <div style="display: flex;justify-content: space-between; padding-top: 20px;">
            <el-button type="primary" icon="el-icon-back" @click="goBack">返回</el-button>
            <span>
                <el-button type="success" icon="el-icon-check" v-if="!isView" @click="saveData">保存</el-button>
                <el-button type="primary" icon="el-icon-menu" @click="goToList">列表</el-button>
                <!-- <button @click="printToPDF">打印PDF</button> -->
                <el-button type="primary" icon="el-icon-printer" @click="printForm">打印</el-button>
            </span>
        </div>
        <div id="format-table">
            <h2 style="text-align: center;">工务/维修申请单</h2>
            <table class="maintenance-table">
                <tbody>
                    <tr>
                        <th rowspan="3">申请部门填写</th>
                        <td>申请部门</td>
                        <td><input v-model="formData.applyDepartment" :readonly="isView"></td>
                        <td>申请日期</td>
                        <td><input type="date" v-model="formData.applyDate" :readonly="isView"></td>
                        <td>公务/维修地点</td>
                        <td><input v-model="formData.maintenanceLocation" :readonly="isView"></td>
                    </tr>
                    <tr>
                        <td><label>维修内容及说明：</label></td>
                        <td colspan="5">
                            <textarea v-model="formData.maintenanceContent" :readonly="isView"></textarea>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="7">
                            <span>总经理批准:<input v-model="formData.generalManagerApproval" :readonly="isView"></span>
                            <span>部长/总监审核:<input v-model="formData.directorReview" :readonly="isView"></span><br>
                            <span>部门经理:<input v-model="formData.departmentManager" :readonly="isView"></span>
                            <span>申请人:<input v-model="formData.applicant" :readonly="isView"></span>
                        </td>
                    </tr>
                    <tr>
                        <th rowspan="5">受理部门填写</th>
                        <td>受理日期</td>
                        <td><input type="date" v-model="formData.acceptDate" :readonly="isView"></td>
                        <td>维修方式</td>
                        <td colspan="3">
                            <label><input type="radio" v-model="formData.maintenanceMethod" value="企业管理部"
                                    :disabled="isView">企业管理部</label>
                            <label><input type="radio" v-model="formData.maintenanceMethod" value="联系外修"
                                    :disabled="isView">联系外修</label>
                            <label><input type="radio" v-model="formData.maintenanceMethod" value="其它"
                                    :disabled="isView">其它</label>
                        </td>
                    </tr>
                    <tr>
                        <td><label>处理方案：</label></td>
                        <td colspan="5">
                            <textarea v-model="formData.solution" :readonly="isView"></textarea>
                        </td>
                    </tr>
                    <tr>
                        <td>费用</td>
                        <td colspan="5">
                            <label>人民币：</label><input style="border-bottom: 1px solid;" v-model="formData.cost"
                                :readonly="isView">（元）;
                            <label>详见：</label><input style="border-bottom: 1px solid;" v-model="formData.costDetails"
                                :readonly="isView">;
                        </td>
                    </tr>
                    <tr>
                        <td>预计完成日期</td>
                        <td colspan="5">
                            <label><input type="radio" v-model="formData.expectedCompletionTime" value="1-3工作日"
                                    :disabled="isView">1-3工作日</label>
                            <label><input type="radio" v-model="formData.expectedCompletionTime" value="3-5工作日"
                                    :disabled="isView">3-5工作日</label>
                            <label><input type="radio" v-model="formData.expectedCompletionTime" value="5-10工作日"
                                    :disabled="isView">5-10工作日</label>
                            <label><input type="radio" v-model="formData.expectedCompletionTime" value="其他"
                                    :disabled="isView">其他</label>
                            <input v-if="formData.expectedCompletionTime === '其他'"
                                v-model="formData.specificExpectedDate" :readonly="isView">
                        </td>
                    </tr>
                    <tr>
                        <td colspan="6">
                            <span>批准:<input v-model="formData.approval" :readonly="isView"></span>
                            <span>审核:<input v-model="formData.review" :readonly="isView"></span><br>
                            <span>行政主管:<input v-model="formData.adminSupervisor" :readonly="isView"></span>
                            <span>受理人:<input v-model="formData.acceptor" :readonly="isView"></span>
                        </td>
                    </tr>
                    <tr>
                        <td rowspan="2">审批</td>
                        <td colspan="2">总经理</td>
                        <td colspan="2">企业管理部</td>
                        <td colspan="2">董事长</td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <label><input type="radio" v-model="formData.generalManagerOpinion" value="同意"
                                    :disabled="isView">同&emsp;意</label><br>
                            <label><input type="radio" v-model="formData.generalManagerOpinion" value="不同意"
                                    :disabled="isView">不同意</label><br>
                            <label><input type="radio" v-model="formData.generalManagerOpinion" value="其他"
                                    :disabled="isView">其&emsp;他</label><br>
                            <p>总经理签字: <input v-model="formData.generalManagerSignature" :readonly="isView"></p>
                        </td>
                        <td colspan="2">
                            <label><input type="radio" v-model="formData.hrDepartmentOpinion" value="同意"
                                    :disabled="isView">同&emsp;意</label><br>
                            <label><input type="radio" v-model="formData.hrDepartmentOpinion" value="不同意"
                                    :disabled="isView">不同意</label><br>
                            <label><input type="radio" v-model="formData.hrDepartmentOpinion" value="其他"
                                    :disabled="isView">其&emsp;他</label><br>
                            <p>企管部签字: <input style="width: 50%;" v-model="formData.hrDepartmentSignature" :readonly="isView"></p>
                        </td>
                        <td colspan="2">
                            <label><input type="radio" v-model="formData.chairmanOpinion" value="同意"
                                    :disabled="isView">同&emsp;意</label><br>
                            <label><input type="radio" v-model="formData.chairmanOpinion" value="不同意"
                                    :disabled="isView">不同意</label><br>
                            <label><input type="radio" v-model="formData.chairmanOpinion" value="其他"
                                    :disabled="isView">其&emsp;他</label><br>
                            <p>董事长签字: <input style="width: 55%;" v-model="formData.chairmanSignature" :readonly="isView"></p>
                        </td>
                    </tr>
                    <tr>
                        <td style="text-align: left;" colspan="7">
                            <span style="display: flex;justify-content: space-between;padding: 5px;">
                                <span>
                                    表单编号及版本：AM-IV-182 A/1
                                </span>
                                <span>
                                    保存期限：长期
                                </span>
                            </span>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</template>

<script>
import { saveMaintenanceForm, getMaintenanceFormById } from '@/api/maintenance'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'

export default {
    data() {
        return {
            formData: {
                applyDepartment: '',
                applyDate: '',
                maintenanceLocation: '',
                maintenanceContent: '',
                generalManagerApproval: '',
                directorReview: '',
                departmentManager: '',
                applicant: '',
                acceptDate: '',
                maintenanceMethod: '',
                solution: '',
                cost: '',
                costDetails: '',
                expectedCompletionTime: '',
                specificExpectedDate: '',
                approval: '',
                review: '',
                adminSupervisor: '',
                acceptor: '',
                generalManagerOpinion: '',
                hrDepartmentOpinion: '',
                chairmanOpinion: '',
                generalManagerSignature: '',
                hrDepartmentSignature: '',
                chairmanSignature: ''
            },
            isView: false
        }
    },
    created() {
        const { id, type } = this.$route.query
        if (id) {
            this.fetchData(id)
            this.isView = type === 'view'
        }
    },
    methods: {
        printForm() {
            window.print()
        },
        formatDate(date) {
            if (!date) return ''
            const d = new Date(date)
            const year = d.getFullYear()
            const month = String(d.getMonth() + 1).padStart(2, '0')
            const day = String(d.getDate()).padStart(2, '0')
            const hours = String(d.getHours()).padStart(2, '0')
            const minutes = String(d.getMinutes()).padStart(2, '0')
            const seconds = String(d.getSeconds()).padStart(2, '0')
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
        },
        parseDate(dateStr) {
            if (!dateStr) return ''
            return dateStr.split('T')[0]
        },
        async fetchData(id) {
            try {
                const result = await getMaintenanceFormById(id)
                if (result.data) {
                    const data = result.data
                    // 处理日期显示
                    data.applyDate = this.parseDate(data.applyDate)
                    data.acceptDate = this.parseDate(data.acceptDate)
                    this.formData = data
                }
            } catch (error) {
                console.error('获取数据失败', error)
                this.$message.error('获取数据失败')
            }
        },
        async saveData() {
            try {
                // 数据验证
                if (!this.formData.applyDepartment) {
                    this.$message.error('申请部门不能为空')
                    return
                }
                if (!this.formData.applyDate) {
                    this.$message.error('申请日期不能为空')
                    return
                }
                if (!this.formData.maintenanceLocation) {
                    this.$message.error('维修地点不能为空')
                    return
                }
                if (!this.formData.maintenanceContent) {
                    this.$message.error('维修内容不能为空')
                    return
                }
                if (!this.formData.applicant) {
                    this.$message.error('申请人不能为空')
                    return
                }
                if (this.formData.cost && isNaN(this.formData.cost)) {
                    this.$message.error('费用必须为数字')
                    return
                }

                // 处理日期格式
                const submitData = { ...this.formData }
                if (submitData.applyDate) {
                    submitData.applyDate = this.formatDate(submitData.applyDate)
                }
                if (submitData.acceptDate) {
                    submitData.acceptDate = this.formatDate(submitData.acceptDate)
                }

                const result = await saveMaintenanceForm(submitData)
                if (result) {
                    this.$message.success('保存成功')
                    this.$router.push('/main/renshi/renshizhidu/gongwuwxsqd/gongwuwxsqdList')
                }
            } catch (error) {
                console.error('保存失败', error)
                this.$message.error('保存失败')
            }
        },
        async printToPDF() {
            const doc = new jsPDF('p', 'pt', 'a4')
            const element = document.querySelector('#format-table')
            await html2canvas(element).then((canvas) => {
                const imgData = canvas.toDataURL('image/png')
                const imgWidth = 522
                const pageHeight = 841.89
                const imgHeight = (canvas.height * imgWidth) / canvas.width
                let positionY = 0
                if (imgHeight >= pageHeight) {
                    let leftHeight = imgHeight
                    while (leftHeight >= pageHeight) {
                        doc.addImage(imgData, 'PNG', 40, positionY, imgWidth, pageHeight)
                        positionY += pageHeight
                        doc.addPage()
                        leftHeight -= pageHeight
                    }
                    doc.addImage(imgData, 'PNG', 40, positionY, imgWidth, leftHeight)
                } else {
                    doc.addImage(imgData, 'PNG', 40, positionY, imgWidth, imgHeight)
                }
            })
            doc.save('工务维修申请单.pdf')
        },
        goToList() {
            this.$router.push('/main/renshi/renshizhidu/gongwuwxsqd/gongwuwxsqdList')
        },
        goBack() {
            this.$router.push('/main/renshi/renshizhidu')
        }
    }
}
</script>

<style scoped>
.container {
    width: 210mm;
    min-height: calc(100vh - 40px);
    margin: 0 auto;
    background-color: #f5f7fa;
    padding: 20px;
}

.maintenance-table {
    border-collapse: collapse;
    width: 100%;
    margin-top: 10px;
    line-height: 30px;
}

.maintenance-table td,
.maintenance-table th {
    border: 1px solid #000;
    padding: 5px 2px;
}

label {
    margin-right: 10px;
}

textarea {
    width: 100%;
    min-height: 60px;
}

input {
    border: 0px;
    background-color: transparent;
}

input[type="radio"] {
    margin-right: 5px;
    height: 13px;
}

/* button {
    margin: 10px;
    padding: 5px 15px;
} */

/* 查看模式下的样式 */
.maintenance-table input[readonly],
.maintenance-table textarea[readonly] {
    background-color: #f5f7fa;
    color: #606266;
    cursor: not-allowed;
}

.maintenance-table input[type="radio"]:disabled+span {
    color: #606266;
}

.maintenance-table input[type="radio"]:disabled {
    cursor: not-allowed;
}

/* 查看模式下的表格样式 */
.maintenance-table td:has(input[readonly]),
.maintenance-table td:has(textarea[readonly]) {
    background-color: #f5f7fa;
}
@media print{
    .el-button{
        display: none;
    }
    textarea{
        resize: none;
    }
}
</style>